const _Promise = require("./bluebird");
// var fundebug = require('../libs/fundebug.1.7.4.min.js');
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
//弹提示框
function alert(obj = {}, showCancel = false) {
  return new _Promise((reslove, reject) => {
    wx.showModal({
      title: obj.title ? obj.title : '',
      content: obj.content ? obj.content : '',
      showCancel: showCancel,
      cancelText: obj.cancelText ? obj.cancelText : '取消',
      confirmText: obj.confirmText ? obj.confirmText : '确定',
      cancelColor: obj.cancelColor ? obj.cancelColor : '#000000',
      confirmColor: obj.confirmColor ? obj.confirmColor : '#3CC51F',
      success: function (res) {
        if (res.confirm) {
          reslove({
            confirm: true
          });
        } else {
          reslove({
            confirm: false
          })
        }
      }
    })
  });
}
//加载
function showLoading(title = '加载中') {
  var time = null;
  if (wx.showLoading) {
    wx.showLoading({
      title: title,
    });
  } else {
    wx.showToast({
      title: title,
      icon: 'loading',
      duration: 1000000
    });
    clearInterval(time);
    time = setInterval(function () {
      // alert({content:'再一次 showLoading'});
      wx.showToast({
        title: title,
        icon: 'loading',
        duration: 1000000
      });
    }, 9000);
  }
  return time;
}

//关闭加载
function hiddenLoading(time) {
  if (wx.showLoading) {
    wx.hideLoading();
  } else {
    clearInterval(time);
    wx.hideToast();
  }
}


function wxPromisify(fn) {
  return function (obj = {}) {
    return new _Promise((resolve, reject) => {
      obj.success = function (res) {
        //成功
        resolve(res)
      }
      obj.fail = function (res) {
        //失败
        reject(res)
        // fundebug.notify("wxPromisify fail, version:" + getApp().globalData.miniVersion, JSON.stringify(res));
      }
      fn(obj)
    })
  }
}

Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => {
      throw reason
    })
  );
};

//页面拦截器
function identityFilter(pageObj) {
  var appData = getApp().globalData;
  if (pageObj.onLoad) {
    let _onLoad = pageObj.onLoad;
    let _onShow = pageObj.onShow;
    pageObj.onLoad = function () {
      //对用户进行校验
      appData.authTokenPromise.then(function () {
        //获取页面实例，防止this劫持
        let currentInstance = getPageInstance();
        currentInstance.setData({
          options: currentInstance.options
        })
        _onLoad.call(currentInstance);
      })
    };

    pageObj.onShow = function () {
      //对用户进行校验
      appData.authTokenPromise.then(function () {
        //获取页面实例，防止this劫持
        let currentInstance = getPageInstance();
        _onShow.call(currentInstance);
      })
    }
  }
  return pageObj;
}

function getPageInstance() {
  var pages = getCurrentPages();
  return pages[pages.length - 1];
}

//时长格式化
function diffTimeFormat(startTime, endTime) {
  if (endTime == null || endTime == '') {
    endTime = Date.now();
  }
  var diffTime = parseInt((endTime - startTime) / 1000);
  var minute = 0;
  var hour = 0;
  var day = 0;
  if (null != diffTime && "" != diffTime) {
    if (diffTime < 3600) {
      diffTime = Math.ceil(diffTime / 60) + "分钟"
    } else if (diffTime >= 3600 && diffTime < 3600 * 24) {
      hour = parseInt(diffTime / 3600);
      minute = Math.ceil((diffTime - (hour * 3600)) / 60);
      diffTime = hour + "小时" + minute + "分钟";
    } else {
      //超过1天
      day = parseInt(diffTime / (3600 * 24));
      hour = parseInt((diffTime - (day * 3600 * 24)) / 3600);
      minute = Math.ceil((diffTime - (day * 3600 * 24) - (hour * 3600)) / 60);
      diffTime = day + "天" + hour + "小时" + minute + "分钟";
    }
  }
  return diffTime;
}

//日期格式化
function formatDate(date) {
  if (!date) return '';
  var date = new Date(date);
  var M = date.getMonth() + 1;
  var y = date.getFullYear();
  var d = date.getDate();
  var H = date.getHours();
  var m = date.getMinutes();
  var s = date.getSeconds();
  if (M < 10) M = "0" + M;
  if (d < 10) d = "0" + d;
  if (H < 10) H = "0" + H;
  if (m < 10) m = "0" + m;
  if (s < 10) s = "0" + s;

  return y + "-" + M + "-" + d + ' ' + H + ':' + m + ':' + s;
}

const getWeekByDate = dates => {
  let show_day = new Array('7', '1', '2', '3', '4', '5', '6');
  let date = new Date(dates);
  date.setDate(date.getDate());
  let day = date.getDay();
  return show_day[day];
}

module.exports = {
  formatTime: formatTime,
  wxPromisify: wxPromisify,
  alert: alert,
  showLoading: showLoading,
  hiddenLoading: hiddenLoading,
  identityFilter: identityFilter,
  formatDate: formatDate,
  diffTimeFormat: diffTimeFormat,
  getWeekByDate: getWeekByDate
}